package com.dollkey.hdownload.activity;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.DownloadListener;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.dollkey.hdownload.R;
import com.dollkey.hdownload.serv.DownLoadNormalService;
import com.dollkey.hdownload.util.HRxBus;
import com.dollkey.hdownload.util.StringUtils;
import com.dollkey.hdownload.util.ValidateUtil;
import com.dollkey.hdownload.util.WebState;
import com.dollkey.hdownload.util.status.StatusBarUtil;
import com.dollkey.hdownload.widget.ProgressWebView;


public class AdWebViewActivity extends AppCompatActivity {
    public static final String ACTION = "com.yoyo.yyadsdk.main.KernelService.WebViewStateReceiver";
    protected Context mContext;
    private ProgressWebView webView;
    private TextView title_tv;
    private boolean goHome;
    private Intent intent;
    private int position;
    private WebState mWebState;

    public static void newInstance(Context context, String url) {
        context.startActivity(newIntent(context, url));
    }


    public static void toBrowser(Context context, String toappUrl) {
        if (!ValidateUtil.isUrl(toappUrl)) {
            toappUrl = "http://".concat(toappUrl);
        }
        Uri uri = Uri.parse(toappUrl);
        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

    public static void newInstance(Context context, String url, boolean goHome) {
        context.startActivity(newIntent(context, url, goHome));
    }

    public static void newInstance(Context context, String url, int type, int position, String contentId, boolean goHome) {
        if (!ValidateUtil.isUrl(url)) {
            url = "http://".concat(url);
        }
        Intent intent = new Intent(context, AdWebViewActivity.class);
        intent.putExtra("url", url);
        intent.putExtra("goHome", goHome);
        intent.putExtra("type", type);
        intent.putExtra("position", position);
        intent.putExtra("contentId", contentId);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

    public static Intent newIntent(Context context, String url) {
        return newIntent(context, url, true);
    }

    public static Intent newIntent(Context context, String url, boolean goHome) {
        if (!ValidateUtil.isUrl(url)) {
            url = "http://".concat(url);
        }
        Intent intent = new Intent(context, AdWebViewActivity.class);
        intent.putExtra("url", url);
        intent.putExtra("goHome", goHome);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        return intent;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Window window = getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED //锁屏状态下显示
//                | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD //解锁
//                | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON //保持屏幕长亮
                | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON); //打开屏幕
        initSystemBar();
        setContentView(R.layout.common_webview);
        mContext = this;
        String url = getIntent().getStringExtra("url");
        final int type = getIntent().getIntExtra("type", -1);
        position = getIntent().getIntExtra("position", -1);
        final String contentId = getIntent().getStringExtra("contentId");
        intent = new Intent("com.yoyo.yyadsdk.main.KernelService.WebViewStateReceiver")
                .putExtra("type", type)
                .putExtra("position", position)
                .putExtra("_id", Integer.valueOf(String.valueOf(System.currentTimeMillis()).substring(5)))
                .putExtra("contentId", contentId);
        mWebState = new WebState();
        mWebState.set_id(Integer.valueOf(String.valueOf(System.currentTimeMillis()).substring(5)));
        mWebState.setType(type);
        mWebState.setPosition(position);
        mWebState.setContentId(contentId);
        if (position > 0) {
//            sendBroadcast(intent.putExtra("anl", 3));
            mWebState.setAnl(3);
            HRxBus.getInstance().post(HRxBus.RX_ACTION_WEB_STATE, mWebState);
        }

        goHome = getIntent().getBooleanExtra("goHome", true);
        webView = findViewById(R.id.web_view);
        title_tv = findViewById(R.id.title_tv);
        findViewById(R.id.cancel_tv).setOnClickListener(v -> close());
        webView.setDownloadListener(new FileDownLoadListener());
        webView.setOnReceivedTitleListener(new ProgressWebView.OnReceivedTitleListener() {
            @Override
            public void onReceivedTitle(String title) {
                title_tv.setText(StringUtils.notNull(title));
            }

            @Override
            public void onReceivedError() {
                if (position > 0) {
//                    sendBroadcast(intent.putExtra("anl", 7));
                    mWebState.setAnl(7);
                    HRxBus.getInstance().post(HRxBus.RX_ACTION_WEB_STATE, mWebState);
                }
            }

            @Override
            public void onPageState(boolean isStart) {
                if (position > 0) {
                    if (isStart) {
//                        sendBroadcast(intent.putExtra("anl", 4));
                        mWebState.setAnl(4);
                    } else {
//                        sendBroadcast(intent.putExtra("anl", 5));
                        mWebState.setAnl(5);
                    }
                    HRxBus.getInstance().post(HRxBus.RX_ACTION_WEB_STATE, mWebState);
                }
            }

            @Override
            public void onPageLoadComplete() {

            }
        });
        webView.loadUrl(url);
        int shortcutId = getIntent().getIntExtra("shortcut", -1);
        if (shortcutId > 0) {
            sendBroadcast(new Intent("com.yoyo.yyadsdk.broad.ShortCutClickReceiver")
                    .putExtra("shortcut", shortcutId));
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (position > 0 && intent != null) {
//            sendBroadcast(intent.putExtra("anl", 6));
            mWebState.setAnl(6);
            HRxBus.getInstance().post(HRxBus.RX_ACTION_WEB_STATE, mWebState);
        }
    }

    /**
     * 当下载文件时打开系统自带的浏览器进行下载，当然也可以对捕获到的 url 进行处理在应用内下载。
     **/
    private class FileDownLoadListener implements DownloadListener {
        @Override
        public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimeType, long contentLength) {
            String fileName = url.substring(url.lastIndexOf("/") + 1);
            startService(new Intent(mContext, DownLoadNormalService.class)
                    .putExtra(DownLoadNormalService.PARAM_APK_URL, url)
                    .putExtra(DownLoadNormalService.PARAM_APK_NAME, fileName));
            // H5中包含下载链接的话让外部浏览器去处理
//            Intent intent = new Intent(Intent.ACTION_VIEW);
//            intent.addCategory(Intent.CATEGORY_BROWSABLE);
//            intent.setData(Uri.parse(url));
//            startActivity(intent);
        }
    }

    @Override
    public void onBackPressed() {
        if (webView.canGoBack())
            webView.goBack();
        else {
            close();
        }
    }

    private void close() {
        if (goHome) {
            Intent intentHome;
            intentHome = new Intent(Intent.ACTION_MAIN);
            intentHome.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intentHome.addCategory(Intent.CATEGORY_HOME);
            startActivity(intentHome);
        }
        finish();
    }

    protected void initSystemBar() {
        //当FitsSystemWindows设置 true 时，会在屏幕最上方预留出状态栏高度的 padding
        StatusBarUtil.setRootViewFitsSystemWindows(this, true);
        //设置状态栏透明
        StatusBarUtil.setTranslucentStatus(this);
        StatusBarUtil.setStatusBarColor(AdWebViewActivity.this, getResources().getColor(android.R.color.white));
        //一般的手机的状态栏文字和图标都是白色的, 可如果你的应用也是纯白色的, 或导致状态栏文字看不清
        //所以如果你是这种情况,请使用以下代码, 设置状态使用深色文字图标风格, 否则你可以选择性注释掉这个if内容
        if (!StatusBarUtil.setStatusBarDarkTheme(this, true)) {
            //如果不支持设置深色风格 为了兼容总不能让状态栏白白的看不清, 于是设置一个状态栏颜色为半透明,
            //这样半透明+白=灰, 状态栏的文字能看得清
            StatusBarUtil.setStatusBarColor(this, 0x55000000);
        }
    }
}
